<template>
  <div class = "">
    <!--  //头部-->
    <el-form
        :inline="true"
        :model="selectByForm"
        class="advanced-form"
        label-position="right"
    >
      <el-row :gutter="20" class="form-row">
        <!-- 第一行 -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="土地" class="form-item">
            <el-input
                v-model="selectByForm.used"
                placeholder="请输入土地目前的作用"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            />
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="项目" class="form-item">
            <el-input
                v-model="selectByForm.itemName"
                placeholder="请输入项目名称"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="总价" class="form-item">
            <el-input
                v-model="selectByForm.totalAmount"
                placeholder="请输入查找总价"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="form-col">
          <el-form-item label="姓名" class="form-item">
            <el-input
                v-model="selectByForm.costName"
                placeholder="请输入购买者姓名"
                clearable
                class="form-input"
                @focus="handleFocus($event)"
                @blur="handleBlur($event)"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮（单独一行） -->
      <el-row>
        <el-col :span="24" class="form-actions">
          <el-button type="primary" @click="onSelect" icon="el-icon-search">查询</el-button>
          <el-button
              type="success"
              @click="toAdd"
              icon="el-icon-plus"
              plain
          >新增
          </el-button>
        </el-col>
      </el-row>
    </el-form>

    <!--  列表页  -->
    <el-table :data="tableData"
              style="width: 100%"
              :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
              stripe
              highlight-current-row
              @current-change="toShow"
              border
    >
      <el-table-column prop="used" label="土地作用" width="180" align="center"  ></el-table-column>
      <el-table-column prop="itemName" label="项目名称" width="180" align="center" ></el-table-column>
      <el-table-column prop="quantity" label="项目数量" width="180" align="center" ></el-table-column>
      <el-table-column prop="unitPrice" label="项目单价" width="180" align="center" ></el-table-column>
      <el-table-column prop="totalAmount" label="项目总支出" width="180" align="center" ></el-table-column>
      <el-table-column prop="costDate" label="支出时间" width="180" align="center" >
        <template slot-scope="scope">
          {{ scope.row.costDate ? scope.row.costDate.split('T')[0] : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="costName" label="支出人" width="180" align="center" ></el-table-column>
      <el-table-column label="操作" width="180" align="center" >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="toUpdate(scope.row)">修改</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--    页脚-->
    <el-pagination
        background
        :page-size="pageSize"
        :current-page="pageNum"
        :page-count="pages"
        layout="prev, pager, next"
        :total="total"
        @current-change="changePageNum"
    >
    </el-pagination>

    <!--    弹窗，实现新增信息-->
    <el-dialog
        title="新增农业支出"
        :visible.sync="addDialog"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="costForm"
          :rules="rules"
          ref="costForm"
          label-position="left"
          class="cost-form"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="土地用途" prop="used">
            <el-select
                v-model="costForm.used"
                placeholder="请选择土地用途"
                filterable
                clearable
                remote
                :loading="usageLoading"
                @focus="loadLandUsageOptions"
            >
              <el-option
                  v-for="item in landUsageOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用项目" prop="itemName">
              <el-input
                  v-model="costForm.itemName"
                  placeholder="费用项目名称"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                  v-model="costForm.quantity"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input-number
                  v-model="costForm.unitPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(元)">
              <el-input
                  :value="(costForm.quantity * costForm.unitPrice).toFixed(2)"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false" size="medium">取 消</el-button>
        <el-button
            type="primary"
            @click="addForm('costForm')"
            size="medium"
            :loading="submitting"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!--    弹窗，实现修改信息-->
    <el-dialog
        title="修改支出"
        :visible.sync="updateDialog"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="costForm"
          :rules="rules"
          ref="costForm"
          label-position="left"
          class="cost-form"
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="土地作用" prop="used">
              <el-input
                  :value="costForm.used"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="费用项目" prop="itemName">
              <el-input
                  v-model="costForm.itemName"
                  placeholder="费用项目名称"
                  clearable
              ></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="数量" prop="quantity">
              <el-input-number
                  v-model="costForm.quantity"
                  :min="0"
                  :step="1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(元)" prop="unitPrice">
              <el-input-number
                  v-model="costForm.unitPrice"
                  :min="0"
                  :precision="2"
                  :step="0.1"
                  controls-position="right"
                  style="width: 100%"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(元)">
              <el-input
                  :value="(costForm.quantity * costForm.unitPrice).toFixed(2)"
                  disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>


      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false" size="medium">取 消</el-button>
        <el-button
            type="primary"
            @click="updateForm('costForm')"
            size="medium"
            :loading="submitting"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {getCostsPage, saveCostsApi, updateCostsApi} from "@/api/costs";
import {getLandUsageListApi} from "@/api/land";

  export default {
    data() {
      return{
        //筛选表单
        selectByForm:{
          used:'',
          itemName:'',
          totalAmount:'',
          costName:''
        },
        //列表数据
        tableData:'',
        //页脚
        pages: 0,
        total: 1,
        pageNum: 1,
        pageSize:6,
        //弹窗 默认值
        addDialog: false,
        updateDialog:false,
        submitting: false,//按钮是否可使用
        costForm: {
          costId:'',
          used:'',
          itemName:'',
          quantity: 0,//数量
          unitPrice: 0,//单价
          totalAmount:0,//总价格
          costName:''
        },
        rules: {
          used: [
            { required: true, message: '请输入土地作用', trigger: 'blur' }
          ],
          itemName: [
            { required: true, message: '请输入费用项目名称', trigger: 'blur' }
          ],
          quantity: [
            { required: true, message: '请输入数量', trigger: 'blur' }
          ],
          unitPrice: [
            { required: true, message: '请输入单价', trigger: 'blur' }
          ]
        },
        landUsageOptions: [], // 土地用途选项
        usageLoading: false // 加载状态
      };
    },
    methods: {

      // 加载土地用途选项
      async loadLandUsageOptions() {
        if (this.landUsageOptions.length > 0) return

        try {
          this.usageLoading = true
          const response = await getLandUsageListApi()
          this.landUsageOptions = response.data.map(item => ({
            value: item.landId, // 假设返回数据有id字段
            label: item.used // 假设返回数据有name字段
          }))
        } catch (error) {
          console.error('获取土地用途列表失败:', error)
          this.$message.error('获取土地用途列表失败')
        } finally {
          this.usageLoading = false
        }
      },


      toUpdate(row){
        console.log(row)
        this.costForm = row
        this.updateDialog = true
      },

      updateForm() {
        this.$refs.costForm.validate(valid => {
          if (valid) {
            this.submitting = true
            // 模拟API调用
            updateCostsApi(this.costForm,sessionStorage.getItem('username')).then(()=>{
              this.submitting = false
              this.updateDialog = false
              this.$message.success('修改成功')
              this.getPage()
            })
          }
        })
      },

      addForm() {
        this.$refs.costForm.validate(valid => {
          if (valid) {
            this.submitting = true
            // 计算总价
            // this.costForm.totalAmount = this.costForm.quantity * this.costForm.unitPrice

            // 模拟API调用
            saveCostsApi(this.costForm,sessionStorage.getItem('username')).then(()=>{
              this.submitting = false
              this.addDialog = false
              this.$message.success('新增成功')
              this.getPage()

            })
          }
        })
      },

      toAdd(){
        this.costForm = {}
        this.addDialog = true
      },

      onSelect(){
        this.pageNum = 1
        this.getPage()
      },

      //获取页面数据
      getPage(){
        getCostsPage(this.selectByForm,this.pageNum,this.pageSize).then((res) =>{
          if(res.code == 200){
            this.tableData = res.data.list
            this.pages = res.data.pages
            this.total = res.data.total
            this.pageNum = res.data.pageNum
            this.pageSize = res.data.pageSize
          }
        })
      },
      //直接选择第几页
      changePageNum(v){
        console.log(v+'')
        this.pageNum = v
        this.getPage()
      }
    },
    created(){
      this.getPage()
    }
  }
</script>

<style scoped>
.form-actions {
  text-align: right;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  margin-top: 10px;
}
/* 表单行样式 */
.form-row {
  margin-bottom: 15px;
}

/* 表单列样式 */
.form-col {
  margin-bottom: 10px;
  padding: 0 10px;
}

/* 表单项样式 */
.form-item {
  margin-bottom: 0;
}

/* 输入框样式 */
.form-input {
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-col {
    padding: 0 5px;
  }
}
.cost-form {
  padding: 0 20px;
}

.dialog-footer {
  text-align: right;
  padding: 15px 20px 0;
  border-top: 1px solid #e8e8e8;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 数字输入框右侧按钮样式 */
.el-input-number__decrease,
.el-input-number__increase {
  background-color: #f5f7fa;
}
</style>

